package tv.accedo.achi.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import tv.accedo.achi.model.Achi;
import tv.accedo.achi.util.SessionFactoryUtil;

/**
 * A dao class with achievement model database operations.
 * @author Bo Liang
 * 
 */
@Component
public class AchiDao {

	private SessionFactory sessionFactory; //injection
	private Achi achi; //injection
	
	/**
	 * Get achievement object by achievement sn.
	 * <p>obtain the achievement object instance by using this achievement serial number<br>
	 * @param	achi_sn	achievement serial number
	 * @return 			achievement object
	 */
	public Achi getAchiByAchisn(String achi_sn) {
		Session session = null; 
		try {
			session = SessionFactoryUtil.getSessionFactory().openSession(); 
//			session = sessionFactory.openSession();
			Query query = session.createQuery("from Achi achi where achi.achi_sn = ?")
						  .setParameter(0, achi_sn); 
			achi = (Achi)query.uniqueResult();  
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			SessionFactoryUtil.closeSession(session);
//			session.close();
		}
		return achi; 
	}
	
	
	/**
	 * Get all achievements which belong to the specific application
	 * <p>By using application's serial number, fetch all this application's achievements into List<br>
	 * @param	app_sn	application serial number
	 * @return			achievements List
	 */
	@SuppressWarnings("unchecked")
	public List<Achi> getAchisByAppsn(String app_sn) {
		List<Achi> achiList = new ArrayList<Achi>();
		Session session = null; 
		try {
			session = sessionFactory.openSession();
			Query query = session.createQuery("from Achi achi where achi.app_sn = ? order by achi.achi_sn desc")
					      .setParameter(0, app_sn); 
			achiList = query.list();  
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		
		return achiList; 
	}
	
	
	public Achi getAchi() {
		return achi;
	}

	@Resource
	public void setAchi(Achi achi) {
		this.achi = achi;
	}


	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
}
